<template>
  <div class="guide">
    <div class="path">
      <q-btn @click="moveFootprint('left')" unelevated class="move-btn move-btn-left"
             style="height:40px;background:#fff;color:#333333;padding:4px 2px;border-radius:0px">
        <q-icon size="1.6em" name="chevron_left" />
      </q-btn>
      <div class="footprint">
        <q-scroll-area ref="footprintScroll" :visible="false" horizontal class="footprint-scroll" :thumb-style="{backgroundColor:'transparent'}">
          <transition-group name="scaleX" tag="ul" class="foot-print-list">
            <li v-ripple v-for="(item) in footprint" :key="item.id"
                @click="goPage(item.link, item)"
                class="foot-print-item relative-position" :class="{'active':pageSelect[pageSelect.length-1].name===item.name}">
              <span class="ellipsis cursor-pointer" style="display: inline-block;width: 84px;vertical-align: middle">{{getMenuName(item)}}</span>
              <q-btn @click.stop="removeFootprint(item)" dense flat size="6px" class="footprint-close"
                     icon="iconfont icontubiao-67" v-show="item.name !== '首页'" />
              <q-menu touch-position context-menu>
                <q-list dense style="min-width: 150px">
                  <q-item clickable v-close-popup @click="removeFootprint(item)" v-show="item.name !== '首页'">
                    <q-item-section>关闭当前</q-item-section>
                  </q-item>
                  <q-item clickable v-close-popup @click="clearFootprint" v-show="item.name !== '首页'">
                    <q-item-section>关闭所有</q-item-section>
                  </q-item>
                  <q-item clickable v-close-popup @click="removeFootprintOther(item)">
                    <q-item-section>关闭其他</q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </li>
          </transition-group>
        </q-scroll-area>
      </div>
      <q-btn @click="moveFootprint('right')" unelevated class="move-btn move-btn-right"
             style="border-right:1px solid #cfd6fe;height:40px;background:#fff;color:#333333;padding:4px 2px;border-radius:0px">
        <q-icon size="1.6em" name="chevron_right" />
      </q-btn>
      <div v-if="!isIMC" class="dashboard" @click="goDashboard"><q-icon name="img:statics/svg/dashboard.svg" class="dashboard-icon margin-r-10"></q-icon> <span class="dashboard-name">可视化报表</span></div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters, mapMutations } from 'vuex'
import { menuListData } from '../../assets/js/menu-list'
import _ from 'lodash'

export default {
  name: 'Footprint',
  computed: {
    ...mapGetters([
      'footprint',
      'pageSelect',
      'permissions',
      'history',
      'statusList'
    ]),
    isHuawei () {
      return this.userInfo.channel === 'hw' && this.userInfo.client_id === 'huawei_iot_stage_app'
    },
    isYQZZ () {
      return this.userInfo.channel === 'hw' && this.userInfo.client_id === process.env.YQZZ_CLIENT_ID
    },
    isIMC () {
      return this.userInfo.client_id === process.env.IMC_CLIENT_ID
    },
    isZhongji () {
      return this.userInfo.tenant_id === '49762054270242817'
    }
  },
  data () {
    return {
      navList: [],
      linkObj: {}
    }
  },
  watch: {
    $route (to, from) {
      this.getMenuActive()
    },
    // 获取动态菜单
    permissions () {
      this.getMenuInfo()
    }
  },
  created () {
    this.getMenuInfo()
  },
  mounted () {
    this.saveCustomerSet()
  },
  methods: {
    ...mapActions([
      'saveCustomerSet'
    ]),
    getMenuName (data) {
      const name = _.replace(data.name, '停机', this.statusList[1].label)
      return name
    },
    goDashboard () {
      if (this.isHuawei) {
        window.open(process.env.DASHBOARD_URL + '?utm_source=huawei', '_blank')
      } else if (this.isYQZZ) {
        window.open(process.env.DASHBOARD_URL + '?utm_source=yqzz', '_blank')
      } else if (this.isZhongji) {
        window.open('http://124.70.74.79:9010/CIMC/#/', '_blank')
      } else {
        window.open(process.env.DASHBOARD_URL, '_blank')
      }
    },
    getMenuInfo () {
      this.setMenuListData()
      this.menuList = this.initMenuList(this.navList)
      this.getMenuActive()
      const result = {}
      this.menuListData.forEach(item => {
        if (item?.children?.length > 0) {
          item.children.forEach(cld => {
            result[cld.link] = true
          })
        }
      })
      this.linkObj = result
    },
    // 初始化menuList数据
    initMenuList (info) {
      let menuList = info.map(item => {
        return {
          ...item,
          open: false
        }
      })
      return menuList
    },
    // 跳转页面
    goPage (link, item) {
      if (item && item.query && JSON.stringify(item.query) !== '{}') {
        this.$router.push({
          path: link,
          query: item.query
        })
      } else {
        this.$router.push(link)
      }
    },
    // 移除一条我的足迹数据
    removeFootprint (removeItem) {
      let isCur = this.pageSelect[this.pageSelect.length - 1].name === removeItem.name
      let curIndex = this.footprint.findIndex(item => item.name === removeItem.name)
      const footprint = this.footprint.filter(item => {
        return item.name !== removeItem.name
      })
      this.set_footprint(footprint)
      let saveDesc = footprint.map(item => {
        return item.desc
      })
      this.saveInfo = saveDesc
      // 如果关闭的是当前一个就跳转到上一个
      if (isCur) {
        if (footprint.length > 0) {
          this.$router.push(
            {
              path: footprint[curIndex - 1].link,
              query: {
                ...footprint[curIndex - 1].query
              }
            }
          )
        } else {
          this.$router.push('/main/home')
        }
      }
    },
    // 移除其他
    removeFootprintOther (item) {
      let footprint
      if (item.name !== '首页') {
        let home = this.footprint.filter(i => {
          return i.name === '首页'
        })
        footprint = [...home, item]
        this.saveInfo = [home.desc, item.desc]
      } else {
        footprint = [item]
        this.saveInfo = [item.desc]
      }
      this.set_footprint(footprint)
      if (this.$route.path !== item.link) {
        this.$router.push(item.link)
      }
    },
    // 清空足迹
    clearFootprint () {
      this.set_footprint([])
      this.$refs.footprintScroll.setScrollPosition(0)
      this.saveInfo = []
      if (this.$route.path !== '/main/home') {
        this.$router.push('/main/home')
      }
    },
    // 获取当前菜单的位置
    getMenuActive () {
      let url = this.$route.path
      // 循环菜单展示情况
      let isFind = this.getChildrenPath(this.menuListData, false, url)
      // 若当前页面存在于菜单中，展开对应菜单项
      if (isFind) {
        // 打开左侧目录的相应位置
        if (this.menuList[this.menuActive[0]]) {
          this.menuList[this.menuActive[0]].open = true
        }
        // 设置面包屑数据
        this.setBreadcrumbs()
        // 设置我的足迹数据
        this.saveFootprint()
      }
    },
    /**
     * refactor 获取菜单函数
     * arr 菜单列表
     * isChildren 是否子集
     * url 路径地址
     */
    getChildrenPath (arr, isChildren, url) {
      let isFind = false
      for (let i = 0; i < arr.length; i++) {
        if (url.includes(arr[i].link)) {
          if (!isChildren) {
            this.menuActive = [i]
            this.setMenuOpen(arr[i])
          } else {
            this.menuActive.push(i)
          }
          isFind = true
          if (Object.is(url, arr[i].link)) {
            break
          }
          let menu1 = arr[i].children
          if (menu1.length > 0) {
            this.getChildrenPath(menu1, true, url)
          }
        }
      }
      return isFind
    },
    // 设置菜单展开
    setMenuOpen (item) {
      for (let i = 0; i < this.menuList.length; i++) {
        if (this.menuList[i].id === item.id) {
          this.menuList[i].open = true
          break
        }
      }
    },
    // 设置面包屑位置的数据
    setBreadcrumbs () {
      let pageSelect = []
      this.menuActive.forEach((item, index) => {
        let data = this.menuListData[this.menuActive[0]]
        if (index > 0) {
          for (let i = 1; i <= index; i++) {
            data = JSON.parse(JSON.stringify(data.children[this.menuActive[i]]))
          }
        }
        const info = {
          id: data.id,
          name: data.name,
          link: index > 0 ? data.link : null
        }
        pageSelect.push(info)
      })
      this.set_page_select(pageSelect)
    },
    // 保存到我的足迹
    saveFootprint () {
      let data = this.menuListData
      for (let i = 0; i < this.menuActive.length; i++) {
        data = data.children ? data.children[this.menuActive[i]] : data[this.menuActive[i]]
      }
      let footprint = JSON.parse(JSON.stringify(this.footprint))
      const findIndex = this.footprint.findIndex(item => {
        return Number(item.id) === Number(data.id)
      })
      let query = this.$route.query
      if (footprint.length === 0 && data.name !== '首页') {
        footprint.push({
          name: '首页',
          link: '/main/home',
          id: 10000,
          desc: 'home',
          query: {}
        })
      }
      if (findIndex === -1) {
        footprint.push({
          name: data.name,
          link: data.link,
          id: data.id,
          desc: this.getKebabCase(data.desc),
          query
        })
        if (footprint.length > 10) {
          let deleteIndex = 0
          footprint = footprint.filter((item, index) => {
            if (item.name === '首页') {
              deleteIndex++
              return true
            }
            return index !== deleteIndex
          })
        }
        this.set_footprint(footprint)
        let saveDesc = []
        footprint.forEach(foot => {
          saveDesc.push(foot.desc)
        })
        this.saveInfo = saveDesc
        this.$nextTick(() => {
          if (this.$refs.footprintScroll && this.$refs.footprintScroll.setScrollPosition) {
            this.$refs.footprintScroll.setScrollPosition(footprint.length * 128, 200)
          }
        })
      } else if (JSON.stringify(query) !== JSON.stringify(footprint[findIndex].query)) {
        footprint[findIndex].query = query
        this.set_footprint(footprint)
      }
      // 设置历史访问记录
      if (data.desc !== 'home' && this.linkObj[data.link]) {
        const history = _.cloneDeep(this.history)
        const index = history.findIndex(item => item.id === data.id)
        // 如果在访问记录中存在的话 就把这条给删了 放在最前面
        if (index > -1) {
          history.splice(index, 1)
        }
        history.unshift({
          name: data.name,
          link: data.link,
          id: data.id,
          desc: this.getKebabCase(data.desc),
          query
        })
        this.set_history(history)
      }
    },
    // 路径导航-左右移动
    moveFootprint (direction) {
      let position = this.$refs.footprintScroll.getScrollPosition()
      position = direction === 'right' ? position + 128 : position - 128
      this.$refs.footprintScroll.setScrollPosition(position, 200)
    },
    // 将驼峰命名的字符串转变成短横线命名的字符串
    getKebabCase (str) {
      return str.replace(/[A-Z]/g, (item) => {
        return '-' + item.toLowerCase()
      })
    },
    setMenuListData () {
      let menuPage = Object.entries(this.Enums.SYS_PERMISSION)
        .filter(entry => (entry[1].type === 'PAGE' || entry[1].type === 'MENU_LEVEL_ONE') && this.permissions.indexOf(entry[1].value) > -1)
      this.menuListData = []
      this.navList = []
      let menuData = JSON.parse(JSON.stringify(menuListData))
      menuData.forEach(menu => {
        let children = null
        let findIndex = menuPage.findIndex(item => {
          return menu.desc === item[1].name
        })
        if (findIndex >= 0) {
          children = menu.children.filter((child, childIndex) => {
            let findIndex2 = menuPage.findIndex(item => {
              return item[1].name === child.desc
            })
            return findIndex2 > -1
          })
          menu.children = children
        }
        if (findIndex >= 0 || menu.name === '首页' || menu.name === '个人中心' || menu.name === '消息列表' || menu.name === '应用商城' || menu.name === '接口配置') {
          this.menuListData.push(menu)
        }
        if (findIndex >= 0) {
          this.navList.push(menu)
        }
      })
    },
    ...mapMutations({
      'set_footprint': 'SET_FOOTPRINT',
      'set_history': 'SET_HISTORY',
      'set_page_select': 'SET_PAGESELECT'
    })
  }
}
</script>

<style scoped lang="stylus">
.dashboard{
  display flex
  align-items center
  height 40px
  width 150px
  cursor pointer;
  padding 0 10px;
  border-radius 0;
  transition background 0.3 cubic-bezier(0.25, 0.8, 0.5, 1)
  &:hover{
    background #cfd6fe
  }

  .dashboard-icon{
    font-size 24px;
  }
}
.guide{
  height 40px
  background-color #ffffff
  box-shadow:0px 1px 1px 0px rgba(0, 0, 0, 0.05)
  display flex
  .path{
    width 100%
    height 100%
    display flex
    justify-content space-between
    font-size 14px
    .footprint{
      flex 1 auto
      .footprint-scroll{
        width 100%
        height 100%
      }
    }
    .foot-print-list{
      white-space nowrap
      color #333
      .foot-print-item{
        display inline-block
        padding 10px 0
        width 120px
        text-align center
        line-height 18px
        border-right 1px solid #cfd6fe
        transform-origin left center
        overflow-x hidden
        white-space: nowrap
        &.active{
          background-color #cfd6fe
        }
        &:hover{
          background-color #e8ebff
        }
      }
      .footprint-close{
        display inline-block
        width 18px
        height 18px
        min-width 18px
        min-height 18px
        margin-left 4px
        color #999
        transition all ease-in .2s
        &:hover{
          color #fff
          background-color rgba(0,0,0,.2)
        }
      }
    }
    .move-btn{
      flex 24px 0
    }
    .move-btn-left{
      box-shadow:1px 0px 3px 0px rgba(0, 0, 0, 0.15);
    }
    .move-btn-right{
      box-shadow:-1px 0px 3px 0px rgba(0, 0, 0, 0.15);
    }
  }
}
</style>
